﻿using System;
using System.Reflection;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Web;
using WcfInspectorLib;

namespace WcfService
{
    public class IISServiceHost : ServiceHost
    {
        public string HttpGetUrl { get; private set; }

        public IISServiceHost(Type serviceType, string httpGetUrl, params Uri[] baseAddress) 
            :base(serviceType, baseAddress)
        {
            HttpGetUrl = httpGetUrl;
        }

        protected override void OnOpening()
        {
            base.OnOpening();

            //自动发布元数据
            Uri httGetUrl = new Uri(HttpGetUrl, UriKind.RelativeOrAbsolute);
            if (!httGetUrl.IsAbsoluteUri)
            {
                Uri baseAddress = BaseAddresses.Where(a => a.Scheme == Uri.UriSchemeHttp).FirstOrDefault();
                if (baseAddress == null) return;
                httGetUrl = new Uri(baseAddress.AbsoluteUri.TrimEnd('/') + "/" + HttpGetUrl);
            }

            ServiceMetadataBehavior mexBehavior = Description.Behaviors.Find<ServiceMetadataBehavior>();
            if (mexBehavior == null)
            {
                mexBehavior = new ServiceMetadataBehavior();
                Description.Behaviors.Add(mexBehavior);
            }

            mexBehavior.HttpGetEnabled = true;
            mexBehavior.HttpGetUrl = httGetUrl;

            //侦听终结点的收发消息事件
            var inspector = new ServerMessageInspector()
                .AddListener<AuthorizeListener>();
            //为每一个终结点都添加监听事件
            foreach (var endpoint in Description.Endpoints)
            {
                endpoint.EndpointBehaviors.Add(inspector);
            }
        }
    }
}